package com.principles.behavior.visitor;

/**
 * @Description 访问者模式：用于封装一些作用于某种数据结构中的各元素的操作，它可以在不改变数据结构的前提下定义作用于这些元素的新的操作
 * @Date 2025/1/31 11:00
 **/
public class VisitorPattern {
    public static void main(String[] args) {
        EggRobot eggRobot = new EggRobot();
        eggRobot.calc();
        Visitor updateVisitor = new UpdateVisitor();
        eggRobot.accept(updateVisitor);
        eggRobot.calc();
    }
}

class EggRobot{

    private HardDisk disk;
    private CPU cpu;

    public EggRobot() {
        cpu = new CPU("1+1=1");
        disk = new HardDisk("记住1+1=1");
    }
    public void calc(){
        cpu.run();
        disk.run();
    }
    public void accept(Visitor visitor){
        cpu.accept(visitor);
        disk.accept(visitor);

    }
}
abstract class HardWare{
    String command;

    public HardWare(String command) {
        this.command = command;
    }
    public void run(){
        System.out.println(command);
    }
    public abstract void accept(Visitor visitor);
}
interface Visitor{
    void visitCPU(CPU cpu);

    void visitHardDisk(HardDisk hardDisk);
}
class UpdateVisitor implements Visitor{

    @Override
    public void visitCPU(CPU cpu) {
        cpu.command ="1+1=2";
        System.out.println("给cpu升级");
    }

    @Override
    public void visitHardDisk(HardDisk hardDisk) {
        hardDisk.command ="记住1+1=2";
        System.out.println("给hardDisk升级");

    }
}
class CPU extends HardWare{

    public CPU(String command) {
        super(command);
    }

    @Override
    public void accept(Visitor visitor) {
        visitor.visitCPU(this);
    }
}
class HardDisk extends HardWare{


    public HardDisk(String command) {
        super(command);
    }

    @Override
    public void accept(Visitor visitor) {
        visitor.visitHardDisk(this);
    }
}